<!--
  MapVerse地图组件
  @description 基于Mars3D的三维地图组件，支持多种图层类型和交互功能
-->
<script setup lang="ts">
// 组件名称遵循多词规范
defineOptions({
  name: 'MapVerseComponent'
})
import { ref, onMounted, onUnmounted, defineExpose, withDefaults } from 'vue'
import { useMapVerse } from './index.js'
import mapManager from './utils/mapManager.js'
import 'mars3d-cesium/Build/Cesium/Widgets/widgets.css'
import 'mars3d/dist/mars3d.css'
interface Props {
  /** 地图容器的DOM ID */
  mapId: string
  /** 地图初始视角类型 (1: 角度1, 其他: 角度2) */
  jiaodu?: number
  /** 是否显示操作按钮（罗盘等） */
  showActions?: boolean
  /** 是否启用地图动画效果 */
  animation?: boolean
  /** 是否显示线条控制按钮 */
  lineControl?: boolean
  /** 是否显示问题类型控制按钮 */
  questionControl?: boolean
  /** 地图类型：offline-离线地图，online-在线天地图 */
  mapType?: 'offline' | 'online'
  /** 底图类型：离线时为global|hebei，在线时为img|vec|ter */
  baseMapType?: string
  /** 是否显示注记（仅在线地图有效） */
  showAnnotation?: boolean
  /** 天地图token */
  tdtToken?: string
}

const props = withDefaults(defineProps<Props>(), {
  mapId: 'mapContainer',
  jiaodu: 1,
  showActions: true,
  animation: true,
  lineControl: false,
  questionControl: false,
  mapType: 'offline',
  baseMapType: '',
  showAnnotation: true,
  tdtToken: '6c99c7793f41fccc4bd595b03711913e',
})

// mapId将直接在useMapVerse中使用props.mapId

interface Emits {
  /** 图层按钮点击事件 */
  layerButtonClick: []
  /** 地图初始化完成事件 */
  initMap: [mapInstance: any]
  /** 线条按钮点击事件 */
  lineButtonClick: []
  /** 问题按钮点击事件 */
  questionButtonClick: []
}

const emit = defineEmits<Emits>()

/** 是否已初始化 */
const initialized = ref(false)

/**
 * 获取当前组件的MapVerse实例
 */
const getMapVerseInstance = (): any => {
  return (window as any)[`mapVerse_${props.mapId}`] || null
}

/**
 * 设置MapVerse实例到window对象
 */
const setMapVerseInstance = (instance: any): void => {
  ;(window as any)[`mapVerse_${props.mapId}`] = instance
}

/**
 * 清理MapVerse实例
 */
const clearMapVerseInstance = (): void => {
  delete (window as any)[`mapVerse_${props.mapId}`]
}

const { initMapVerse, destroy, switchBaseMap, getCurrentBaseMaps } = useMapVerse({
  mapId: props.mapId,
  jiaodu: props.jiaodu,
  showActions: props.showActions,
  animation: props.animation,
  lineControl: props.lineControl,
  questionControl: props.questionControl,
  mapType: props.mapType,
  baseMapType: props.baseMapType || (props.mapType === 'online' ? 'img' : 'hebei'),
  showAnnotation: props.showAnnotation,
  tdtToken: props.tdtToken,
})

onMounted(async () => {
  try {
    console.log('initMapVerse')

    // 初始化MapVerse实例并挂载到window对象
    const mapVerseInstance = await initMapVerse()
    setMapVerseInstance(mapVerseInstance)

    // 注册到全局地图管理器
    mapManager.register(props.mapId, mapVerseInstance)
    initialized.value = true

    // 发射初始化完成事件
    emit('initMap', mapVerseInstance.getMapInstance())

    // 绑定事件监听
    mapVerseInstance.on('layerButtonClick', () => {
      emit('layerButtonClick')
    })

    mapVerseInstance.on('lineButtonClick', () => {
      emit('lineButtonClick')
    })

    mapVerseInstance.on('questionButtonClick', () => {
      emit('questionButtonClick')
    })
  } catch (error) {
    console.error('MapVerse initialization failed:', error)
  }
})

onUnmounted(() => {
  // 从全局地图管理器注销实例
  mapManager.unregister(props.mapId)
  // 清理MapVerse实例
  clearMapVerseInstance()
  destroy()
})

defineExpose({
  // 核心方法
  getMapInstance: () => getMapVerseInstance()?.getMapInstance(),
  getMapVerse: () => getMapVerseInstance(),

  // 基础图层操作
  addWmsLayer: (options: any) => getMapVerseInstance()?.addWmsLayer(options),
  removeLayer: (id: string) => getMapVerseInstance()?.removeLayer(id),

  // 底图切换
  switchBaseMap: (options: any) => switchBaseMap(options),
  getCurrentBaseMaps: () => getCurrentBaseMaps(),

  // 矢量图层操作
  addTowerLayer: (options: any) => getMapVerseInstance()?.businessLayers?.addTowerLayer(options),
  addLineLayer: (options: any) => getMapVerseInstance()?.businessLayers?.addLineLayer(options),
  addSubstationLayer: (options: any) =>
    getMapVerseInstance()?.businessLayers?.addSubstationLayer(options),
  addSensitiveAreaLayer: (options: any) =>
    getMapVerseInstance()?.businessLayers?.addSensitiveAreaLayer(options),
  addSensitiveAnalyseLayer: (options: any) =>
    getMapVerseInstance()?.businessLayers?.addSensitiveAnalyseLayer(options),

  // CustomMap 兼容API
  addVectorTower: (options: any) => getMapVerseInstance()?.businessLayers?.addVectorTower(options),
  addVectorSubStation: (options: any) =>
    getMapVerseInstance()?.businessLayers?.addVectorSubStation(options),
  removeVectorById: (id: string) => getMapVerseInstance()?.businessLayers?.removeVectorById(id),
  addPolygonJson: (options: any) => getMapVerseInstance()?.businessLayers?.addPolygonJson(options),
  addPolylineJson: (options: any) =>
    getMapVerseInstance()?.businessLayers?.addPolylineJson(options),
  addPointJson: (options: any) => getMapVerseInstance()?.businessLayers?.addPointJson(options),

  // 地图控制
  flyToPoint: (lng: number, lat: number, options?: any) =>
    getMapVerseInstance()?.flyToPoint(lng, lat, options),

  // 绘制功能
  startDraw: (type: string, options?: any) => getMapVerseInstance()?.startDraw(type, options),

  // 测量功能
  startMeasure: (type: string, options?: any) => getMapVerseInstance()?.startMeasure(type, options),

  // 工具方法
  toggleFullscreen: () => getMapVerseInstance()?.toggleFullscreen(),

  // 状态检查
  isInitialized: () => initialized.value,
})
</script>

<template>
  <!-- 地图容器 -->
  <div class="custom_hidden_mapbox">
    <div class="custom_map_container">
      <!-- Mars3D地图渲染容器 -->
      <div class="cesiumMap" id="globalStatisticsMap" @contextmenu.prevent></div>
    </div>
  </div>
</template>
<style lang="scss" scoped src="./index.scss"></style>
